"""
cron: 30 06 * * *
new Env('京东极速版天天领红包');
"""

import requests
import json
import time
import os
import re
import sys
import random
import string
import urllib
from urllib.parse import quote
import logging

logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

# 获取cookie
def get_cookie():
    url='http://127.0.0.1:5700/api/envs'
    try:
        filePath = '/ql/data/config/auth.json';
        if os.path.exists(filePath) == False:
            filePath = '/ql/config/auth.json';
        with open(filePath, 'r') as f:
            token=json.loads(f.read())['token']
        headers={
            'Accept':'application/json',
            'authorization':'Bearer '+token,
            }
        response=requests.get(url=url,headers=headers)
        data = json.loads(response.text)['data'];
        cookies = [];
        for i in range(len(data)):
            if data[i]['name']=='JD_COOKIE' and data[i]['status'] == 0:
                cookie = data[i]['value'];
                cookies = cookies + cookie.split('&');

        return cookies;
    except:
        logger.info('读取auth.json文件出错，跳过获取备注')
    return '';

# 获取header
def get_header(cookie):
    headers = {
      'Host': 'api.m.jd.com',
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Origin': 'https://prodev.m.jd.com',
      'Accept-Language': 'zh-cn',
      'User-Agent': "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
      'Referer': 'https://prodev.m.jd.com',
      'Accept-Encoding': 'gzip, deflate, br',
      'Cookie': cookie
    }
    return headers;

# 领取红包
def open_redpack(cookie):
    logger.info('开始领取红包');
    url = 'https://api.m.jd.com/?functionId=spring_reward_receive&body={"inviter":"","linkId":"Eu7-E0CUzqYyhZJo9d3YkQ"}&t=1650007515615&appid=activities_platform&h5st=20220415152516550;1169703826744965;07244;tk02wbd051c6318nDRmcp4GVnHYpxFuDpxDOs/yVGqGV/mMlYRlrCRbWw4Mn3MCw5/2LCllLAjekl0d+m+uwcZTqOJNM;463244234d72b1af9a9b5dec88f10cb364614d280efdfaee99f7568e5312d4bf;3.0;1650007516550';
    headers = get_header(cookie);
    response=requests.get(url=url,headers=headers)
    data = json.loads(response.text);
    if data['success'] == True:
        data = data['data'];
        freeNumber = data['remainChance']; # 第1次是2，第2次是1 
        if freeNumber >= 0 : 
            received = data['received']
            typeName = received['prizeDesc'];
            logger.info("获得" + str(received['amount']) + typeName)
            if freeNumber > 0:
                time.sleep(2);
                open_redpack(cookie);
        else:
            logger.info("领取完成")
    else:
        logger.info(data)

# 签到提现
def sign_with(cookie):
    logger.info('开始京东极速版签到');
    url = 'https://api.m.jd.com/?functionId=getStaticResource&body={"linkId":"9WA12jYGulArzWS7vcrwhw"}&t=' + getTime() + '&appid=activities_platform&client=H5&clientVersion=1.0.0'
    headers = get_header(cookie);
    response=requests.get(url=url,headers=headers)
    data = json.loads(response.text);
    if data['success'] == True:
        logger.info("签到成功，正在查询获取的奖品。等待2秒");
        time.sleep(2);
        # 查询获得的信息
        url = 'https://api.m.jd.com/';
        data = 'functionId=apSignIn_day&body={"linkId":"9WA12jYGulArzWS7vcrwhw","serviceName":"dayDaySignGetRedEnvelopeSignService","business":1}&t=' + getTime() + '&appid=activities_platform&client=H5&clientVersion=1.0.0&h5st=20220415155415416%3B6335201798883713%3B15097%3Btk02w92ea1c3418nRH9RF4ZX7rWsdSXq0OZ4zpDHekiG7TPeYN7GMdr8AZtIpC3lLjx%2FYMmQucW2uP8wVxAZgnjYzPDN%3B69754229f2c4817b39e01a376f002608213168b2cb8fe173facc5758e83801ce%3B3.0%3B1650009255416';
        response=requests.post(url=url,headers=headers, data=data)
        data = json.loads(response.text);
        if data['success'] == True:
            data = data['data'];
            # 当前是第几天
            if data['retCode'] == 0:
                currentDay = time.strftime("%Y-%m-%d", time.localtime(time.time()))
                historySignInAnCycle = data['historySignInAnCycle']
                for index,value in enumerate(historySignInAnCycle):
                    signDayTime = int(value['signDateStamp']) / 1000;
                    signDay = time.strftime("%Y-%m-%d", time.localtime(signDayTime))
                    if currentDay == signDay:
                        typeName = '现金' if value['signPrizeType'] == 4 else '红包';
                        logger.info("获得" + str(value['prizeAwardVale']) + typeName)
                        if value['signPrizeType']:
                            time.sleep(1);
                            with_money(with_money);
            else:
                logger.info(data)
        else:
            logger.info(data)

# 提现现金
def with_money(cookie):
    url = 'https://api.m.jd.com/';
    data = 'functionId=signPrizeDetailList&body={"linkId":"9WA12jYGulArzWS7vcrwhw","serviceName":"dayDaySignGetRedEnvelopeSignService","business":1,"pageSize":20,"page":1}&t=' + getTime() + '&appid=activities_platform&client=H5&clientVersion=1.0.0';
    headers = get_header(cookie);
    response=requests.post(url=url,headers=headers,data=data)
    data = json.loads(response.text);
    if data['success'] == True and data['data']['code'] == 0:
        data = data['data']['prizeDrawBaseVoPageBean'];
        listItem = data['items'];
        if len(listItem) > 0:
            first = listItem[0];
            if first['prizeType'] == 4:
                firstId = str(first['id'])
                prizeGroupId = str(first['prizeGroupId'])
                prizeBaseId = str(first['prizeBaseId'])
                logger.info('将要提现：' + first['prizeValue'])
                params = 'functionId=apCashWithDraw&body={"linkId":"9WA12jYGulArzWS7vcrwhw","businessSource":"DAY_DAY_RED_PACKET_SIGN","base":{"prizeType":4,"business":"dayDayRedPacket","id":' + firstId + ',"poolBaseId":127,"prizeGroupId":' + prizeGroupId + ',"prizeBaseId":' + prizeBaseId + '}}&t=' + getTime() + '&appid=activities_platform&client=H5&clientVersion=1.0.0'
                response=requests.post(url=url,headers=headers,data=params)
                data = json.loads(response.text);
                if data['success'] == True:
                    logger.info(data['data']['message'])
                else:
                    logger.info('提现失败')
                    logger.info(data)
            else:
                logger.info('没有要提现的金额')
        else:
            logger.info('没有奖品列表')
            logger.info(listItem)
    else:
        logger.info(data)

# 获取时间戳
def getTime():
    return str(int(time.time() * 1000));

def run():
    # 读取多cookie
    cookies = get_cookie()
    for cookie in cookies:
        startIndex = cookie.rindex('pt_pin');
        userName = cookie[startIndex:len(cookie)].replace('pt_pin=' , '');
        logger.info('===========京东账号' + userName + '=========')
        open_redpack(cookie);
        time.sleep(1);
        sign_with(cookie);
        time.sleep(1);

if __name__ == '__main__':
    run()